import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class TCP{
	Socket s;
	PrintWriter pf;
	ObjectOutputStream po;
	BufferedReader bf;
	ObjectInputStream bo;
	
	public TCP(String adresse, int port) throws UnknownHostException, IOException {
		s = new Socket(adresse,port);
	}
	
	public TCP(Socket s) {
		this.s=s;
	}

	public void ouvrirLecture(){
		try{
			bf = new BufferedReader(new InputStreamReader(s.getInputStream()));

		}catch(IOException io){
			System.out.println("echec de l'ouverture en lecture");
			io.printStackTrace();
		}
	}
	
	public void ouvrirEcriture(){
		try{
			pf = new PrintWriter(s.getOutputStream(),true);
			
			
		}catch(IOException io){
			System.out.println("echec de l'ouverture en ecriture");
			io.printStackTrace();
		}
	}
	
	public void ecrire(String s){
		pf.println(s);
	}
	
	public String lire(){
		String t="";
		try{
			t = bf.readLine();
		}catch(IOException io){
			System.out.println("echec de lecture");
			io.printStackTrace();
		}
		return t;
	}
	
	public void envoyerObjet(Object o){
		try {

			po = new ObjectOutputStream(s.getOutputStream());
			po.writeObject(o);
		} catch (IOException e) {
			System.out.println("echec envoi objet");
			e.printStackTrace();	
		}
		
	}
	
	public Object recevoirObjet() throws ClassNotFoundException, IOException{
		bo = new ObjectInputStream(s.getInputStream());
		Object o = bo.readObject();
		return o;
	}
	
	public void openSession(){
		ouvrirLecture();
		ouvrirEcriture();
	} 
	
	public void closeSession(){
		try{ 
			bf.close();
			pf.close();
			po.close();
			bo.close();
			s.close();
		}catch(IOException io){
			System.out.println("echec de fermeture");
			io.printStackTrace();		
		}
	}
	
	public boolean isConnected(){
		return s.isConnected();
	}
}